package com.zl.Sqlite.db;

import android.content.Context;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * User: c3t
 * Date: 14-5-2
 * Time: 上午5:10
 */
public class UserDao {
    private SQLiteTemplate sqLiteTemplate;

    public UserDao(Context context) {
        sqLiteTemplate = new SQLiteTemplate(context);
    }

    /**
     * 添加一个用户
     *
     * @param name 要添加的用户名
     */
    public void add(String name) {
        String sql = "insert into user(name) values(?)";
        Object[] objs = {name};
        sqLiteTemplate.add(sql, objs);
    }

    /**
     * 查找用户是否存在
     *
     * @param name 要查找的用户名
     */
    public boolean find(String name) {
        String sql = "select * from user where name = ?";
        String[] args = {name};
        return sqLiteTemplate.find(sql, args).isExist();
    }

    /**
     * 更新用户名
     *
     * @param name 新用户名
     * @param id   被更新的用户id
     */
    public void update(String name, int id) {
        String sql = "update user set name = ? where id = ?";
        Object[] objs = {name, id};
        sqLiteTemplate.update(sql, objs);
    }

    /**
     * 根据id删除用户
     *
     * @param id
     */
    public void delete(int id) {
        String sql = "delete from user where id = ?";
        Object[] objs = {id};
        sqLiteTemplate.delete(sql, objs);
    }

    /**
     * 得到所有用户
     * @return
     */
    public List<User> findAll() {
        String sql = "select * from user";
        ResulstObject ro = sqLiteTemplate.find(sql);
        List<User> users = new ArrayList<>();
        List list = ro.getResult();
        for (int i = 0; i < list.size(); i++) {
            Map m = (Map) list.get(i);
            User u = new User((Integer)m.get("id"), String.valueOf(m.get("name")));
            users.add(u);
        }
        return users;
    }
}
